package edu.winona.csclub.testing.gui.html;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;

import edu.winona.csclub.testing.core.Test;
import edu.winona.csclub.testing.core.Value;
import edu.winona.csclub.testing.gui.ExtFileFilter;
import edu.winona.csclub.testing.gui.TestsTableModel;
import edu.winona.csclub.testing.gui.TestsView;

public class HTMLGenerator {

	private static String generateHeader(String style){
		return "<html><head>"+style+"</head><body><table><tr><th>Test Values</th><th>Test Result</th></tr>";
	}
	
	private static String getDefaultStyle(){
		return " <style language=\"css\"> " +
				".fail { color : red }" +
				".suc {color:green}"+
				"tr { background : #ccd } table { 	border-width: 1px 1px 1px 1px; 	border-spacing: 2px; 	border-style: outset outset outset outset; 	border-color: gray gray gray gray; 	border-collapse: separate; 	background-color: #aac; } "+
				"</style>";
	}
	
	private static String testRow(Test t, TestsView tv){
		String ret = "";
		if(TestsTableModel.map.get(t)==null ||  !TestsTableModel.map.get(t).booleanValue() ){
			ret+=" <tr class=\"fail\">";
		} else ret+=" <tr class=\"suc\">";
			
		
		String r = t.getCommand().getValue();
		for( Value v : t.getVariables() ){
			String id = v.getVariable().getId();
			int ind = r.indexOf(id);
			String pref = r.substring(0,ind);
			String post = r.substring(ind+id.length());
			r=pref+v.getValue()+post;
		}
		r=r.substring(r.indexOf(" ")+1);
		r=r.substring(r.indexOf(" ")+1);
		
		ret+="<td class=\"test\">"+r+"</td>";
		ret+= " <td class=\"result\">"+tv.result.get(t).getResult()+"</td>";
		
		ret+= " </tr> ";
		return ret;
	}
	
	private static String generateTail(){
		return "</table></body></html>";
	}
	
	public static void save(TestsView tv) throws IOException{
		JFileChooser sav = new JFileChooser();
		sav.setDialogType(JFileChooser.SAVE_DIALOG);
		sav.setFileFilter(new ExtFileFilter("html"));
		sav.showSaveDialog(tv.getParent() );
		File f = sav.getSelectedFile();
		
		FileWriter fw = new FileWriter(f);
		String res="";
		
		res+= generateHeader(getDefaultStyle());
		for( Test t : tv.getTests() ){
			res+= testRow(t, tv);
		}
		res+= generateTail();
		fw.write(res);
		fw.flush();
		fw.close();
	}
}
